package com.logger;

import com.pojo.SysLog;
import com.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.Date;

/**
 * @author mornd
 * @date 2020/11/28 - 12:40
 */

/**
 * 打印系统日志
 */
@Aspect
@Component
public class  LogAop {
    @Resource
    private HttpServletRequest request;//在当前对象中获取request  前提：在web.xml中配置监听器 RequestContextListener
    @Resource
    private SysLogService sysLogService;
    //开始访问时间
    private Date visitTime;

    //切入点方法
    @Pointcut("execution(* com.controller..*.*(..))")
    public void pt() {
    }

    @Before("pt()")
    public void doBefore() {
        visitTime = new Date();//获取操作时间
    }

    @After("pt()")
    public void doAfter(JoinPoint jp) throws Exception {
        String clazz = jp.getTarget().toString();//获取目标类名
        clazz = clazz.substring(0, clazz.indexOf('@'));
        //如果访问的是页面跳转控制器或者日志控制器则不需记录
        if ("com.controller.PageTransitController".equals(clazz) || "com.controller.SysLogController".equals(clazz) || "com.controller.LeftMenuController".equals(clazz)) {
            return;
        }
        String method = jp.getSignature().getName();//获取目标方法名
        String url = request.getRequestURI();//获取访问的url
        Long time = new Date().getTime() - visitTime.getTime();//获取访问的时长
        //获取访问的IP地址
        InetAddress addr = InetAddress.getLocalHost();
        String ip = addr.getHostAddress();
        //获取当前操作的用户
        SecurityContext context = SecurityContextHolder.getContext();
        User user = (User) context.getAuthentication().getPrincipal();//security对象中的User
        //创建系统日志对象
        SysLog sysLog = new SysLog();
        sysLog.setVisitTime(visitTime);
        sysLog.setUserName(user.getUsername());
        sysLog.setIp(ip);
        sysLog.setUrl(url);
        sysLog.setExecutionTime(time);//访问时长
        sysLog.setClassName(clazz);//获取类名
        sysLog.setMethod(method);//获取方法名
        //保存至数据库
        sysLogService.saveLog(sysLog);
    }

}
